#!/bin/bash

DISABLE_LIBS="libpng libjpeg libtiff libmspack gtkprint gnomeprint regex zlib expat"
CPPFLAGS="-ffunction-segments"

OPT="--enable-unicode"
while read NAME COMMENT
do
	if [ "${NAME:0:1}" = "-" ]; then
		OPT=$OPT" --disable-${NAME:1}";
	fi
	if [ "${NAME:0:1}" = "+" ]; then
		OPT=$OPT" --enable-${NAME:1}";
	fi
done < components

for x in $DISABLE_LIBS
do
	OPT=$OPT" --without-$x"
done

if [ "$1" = "debug" ]; then
	OPT=$OPT" --enable-debug --enable-shared"
elif [ "$1" = "release" ]; then
	OPT=$OPT" --disable-debug --disable-debug_flag --disable-shared --without-subdirs --enable-no_rtti"
	CFLAGS=" -flto -fdata-sections -ffunction-sections" 
	CPPFLAGS=" -flto -fdata-sections -ffunction-sections" 
	CXXFLAGS=" -flto -fdata-sections -ffunction-sections" 
	LDFLAGS=" -flto -Wl,--gc-sections "
elif [ "$1" = "release-llvm" ]; then
	OPT=$OPT" --disable-debug --disable-debug_flag --disable-shared --without-subdirs --enable-no_rtti"
    export CC=clang
    export CXX=clang++
    #unfinished - both should have LD_PRELOAD and --plugin, but for AR it's not so simple to set by envvars
    #we'll probably have to edit makefile after the ./configure is done    
    #export AR="a--plugin /usr/lib/LLVMgold.so"
    #export RANLIB="ranlib --plugin /usr/lib/LLVMgold.so"
    
	CFLAGS=" -O4 -flto -fdata-sections -ffunction-sections" 
    CPPFLAGS=" -O4 -flto -fdata-sections -ffunction-sections" 
    CXXFLAGS=" -O4 -flto -fdata-sections -ffunction-sections"
    LDFLAGS="-O4 -flto -Wl,-plugin /usr/lib/LLVMgold.so"
    # due to https://bugs.launchpad.net/ubuntu/+source/llvm-3.0/+bug/1026359
    # one also has to LD_PRELOAD libLTO.so
else
	echo "Specify target: debug or release"
	exit 1
fi

# wxGTK-2.8 specific overrides
if [[ "$OPT" == *--enable-aui* ]]; then
    OPT=$OPT" --enable-timer"   #wxAuiFrameManager requires timer
    OPT=$OPT" --enable-toolbar" #wxAuiFrameManager requires toolbar
fi
if [[ "$OPT" == *--enable-notebook* ]]; then
    OPT=$OPT" --enable-imaglist"   #wxNOtebook requires wxImageList
fi


export CFLAGS=$CFLAGS
export CPPFLAGS=$CPPFLAGS 
export CXXFLAGS=$CXXFLAGS
export LDFLAGS=$LDFLAGS
./configure $OPT
